// 这个文件，专门处理用户相关的
const express = require("express");
const router = express.Router();
var ObjectId = require("mongodb").ObjectId;
const OrderModel = require("../models/order");

// 添加订单 传参:userId,goodsLists,total,subOrderTime(时间戳)
router.post("/addOrder", async (req, res) => {
  const userId = req.body.userId;
  const goodsLists = req.body.goodsLists || "[]";
  let goodsList = JSON.parse(goodsLists);

  let result = goodsList.reduce(function(total, value) {
    return total + value.price * value.num;
  }, 0);
  const total = result;
  let nowTime = new Date();
  const subOrderTime = nowTime.getTime();

  const order = new OrderModel({
    userId,
    goodsLists,
    total,
    subOrderTime
  });

  await order.save();

  res.send({
    code: 0,
    msg: "注册成功"
  });
});

// 删除订单 传参:orderId
router.post("/delOrderInfo", async (req, res) => {
  const orderId = req.body.orderId;
  await OrderModel.deleteOne({ _id: ObjectId(orderId) }, { justOne: true });
  res.send({
    code: 0,
    msg: "删除成功"
  });
});

// 查询所有订单信息 不需要传参
router.post("/findAllOrderInfo", async (req, res) => {
  const orderList = await OrderModel.find();
  let data = orderList;
  res.send({
    code: 0,
    msg: "查询成功",
    data
  });
});

// 根据用户ID查询 传参:userId
router.post("/findOrderInfoByUserId", async (req, res) => {
  const userId = req.body.userId;
  const order = await OrderModel.find({ userId });
  let data = order;

  res.send({
    code: 0,
    msg: "查询成功",
    data
  });
});

// 修改订单信息 传参:orderId(必填) userId goodsLists(选填)
router.post("/upDateOrderInfo", async (req, res) => {
  const orderId = req.body.orderId;

  const order = await OrderModel.find({ _id: ObjectId(orderId) });

  const userId = req.body.userId || order[0].userId;
  const goodsLists = req.body.goodsLists || order[0].goodsLists;
  let result = null;

  if (req.body.goodsLists) {
    let goodsList = JSON.parse(goodsLists);
    result = goodsList.reduce(function(total, value) {
      return total + value.price * value.num;
    }, 0);
  }

  const total = result || order[0].total;

  await OrderModel.updateOne(
    { _id: orderId },
    { $set: { userId, goodsLists, total } }
  );

  res.send({
    code: 0,
    msg: "修改成功"
    // data
  });
});

module.exports = router;
